package com.hao.shiro.realm;

import com.hao.shiro.service.SecurityService;
import com.hao.shiro.service.impl.SecurityServiceImpl;
import com.hao.shiro.tools.DigestsUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author 97472
 * @version 1.0
 * @date 2021/8/30 15:18
 */
public class DefinitionRealm extends AuthorizingRealm {
    public DefinitionRealm() {
        // 设置密码匹配器
        //指定密码匹配方式为sha1
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(DigestsUtil.HASH_ALGORITHM_NAME);
        // 指定密码匹配器迭代的次数
        matcher.setHashIterations(DigestsUtil.ITERATIONS);
        // 将其设置为Realm的密码匹配器
        this.setCredentialsMatcher(matcher);
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 拿到凭证
        String principal = (String) principals.getPrimaryPrincipal();
        // 创建查询服务
        SecurityService securityService = new SecurityServiceImpl();
        // 通过凭证来查询角色和权限
        List<String> roles = securityService.getRoleByLoginName(principal);
        List<String> permissions = securityService.getPermissionByLoginName(principal);
        // 创建角色权限信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        SecurityService securityService = new SecurityServiceImpl();
        Map<String, String> map = securityService.findPasswordByLoginName(principal);
        if (map.isEmpty()){
            throw new UnknownAccountException("账户不存在");
        }
        String salt = map.get("salt");
        String password = map.get("password");
        //传递账号和密码:参数1：缓存对象，参数2：明文密码，参数三：字节salt,参数4：当前DefinitionRealm名称
        return new SimpleAuthenticationInfo(principal,password, ByteSource.Util.bytes(salt),getName());
    }
}
